<template>
  <div v-if="isStep1 == 1" class="step1">
    <div class="flex justify-between items-center mb-4">
      <div class="text-lg font-bold flex center">
        <svg-icon class="text-[20px] text-white" name="Notify" />
        {{ $t("layer.notify.Notifications") }}
      </div>
      <button class="text-gray-400 flex">
        <svg-icon
          v-debounce="readAll"
          class="mr-4 text-gray-400 text-[18px] hover:text-gray-200 cursor-pointer"
          name="clear"
        />

        <van-icon
          @click="closeNotify"
          class="cursor-pointer hover:text-gray-200"
          name="cross"
        />
      </button>
    </div>
    <div class="list-box" @scroll="scrolling">
      <div class="mb-4">
        <span class="text-sm"
          >{{ $t("layer.notify.unread") }}({{ unread_num }})</span
        >
      </div>
      <div v-if="!loading">
        <!-- v-for="(item, i) in notifyList" -->

        <div
          v-for="(item, i) in notifyList"
          :key="i"
          @click="goToDetail(item)"
          class="flex mb-2 notification-item cursor-pointer"
        >
          <div class="flex relative">
            <div
              class="bg-[#1a2c38] w-[62px] rounded-l-lg flex items-center p-2"
            >
              <img v-if="item.type == 'vip'" :src="typeVip" alt="" />
              <img v-else-if="item.type == 'active'" :src="typeActive" alt="" />
              <img
                v-else-if="item.type == 'deposit'"
                :src="typeDeposit"
                alt=""
              />
              <img
                v-else-if="item.type == 'withdrawal'"
                :src="typeWithdrawal"
                alt=""
              />
              <img v-else :src="typeDefault" alt="" />
            </div>
            <div class="flex-1 py-2 bg-[#293c4a] p-2 rounded-r-lg">
              <p class="text-sm text-[#9aa4bb] line-clamp-2">
                {{ item.content }}
              </p>
              <p class="text-xs text-[#748195] mt-2">
                {{ item.created_at }}
              </p>
            </div>
            <div class="ml-2 absolute right-2 bottom-[0.8rem]">
              <div
                v-if="item.status == 1"
                class="w-[8px] h-[8px] bg-green-500 rounded-[50%]"
              ></div>
              <div
                v-else
                class="w-[8px] h-[8px] bg-[#b1bad3] rounded-[50%]"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div v-if="isStep1 == 2" class="step2">
    <div class="mb-4 flex justify-between items-center">
      <a @click="backToStep1" class="text-sm text-blue-400 backIcon">
        &lt; {{ $t("layer.notify.back") }}
      </a>
      <van-icon
        @click="backToStep1"
        class="cursor-pointer ml-[auto] backIcon2"
        name="cross"
      />
    </div>
    <div class="mb-4">
      <div class="text-sm"></div>
      <div class="text-sm text-gray-400">
        <span class="font-bold">
          {{ $t("layer.notify.dataTime") }}: {{ details.created_at }}
        </span>
      </div>
    </div>
    <div class="bg-gray-700 p-4 rounded-lg">
      <div class="text-sm font-bold mb-2">{{ details.title }}</div>
      <div class="text-sm text-gray-300">
        {{ details.content }}
      </div>
    </div>
  </div>
</template>
<script setup name="notify">
// import { closeNotify } from "vant";
import {
  ref,
  onMounted,
  onActivated,
  onBeforeUnmount,
  watch,
  computed
} from "vue";
import {
  msgList1,
  msgDetail,
  msgRead,
  msgRemove,
  msgReadAll
} from "../../api/msg";
import { dateTimeZone } from "../../utils/date";
import { mainAct } from "@/store/activeda";
import typeActive from "../../assets/imgs/notify-active.png";
import typeDeposit from "../../assets/imgs/notify-ch.png";
import typeDefault from "../../assets/imgs/notify-type.png";
import typeVip from "../../assets/imgs/notify-vip.png";
import typeWithdrawal from "../../assets/imgs/notify-wh.png";
import { useI18n } from "vue-i18n";
import i18n from "@/lang";

const { t } = useI18n();
const main = mainAct();
const loading = ref(true);
const props = defineProps(["notifyShow"]);
const emit = defineEmits(["notifyClose"]);
const isStep1 = ref(1);
const notifyList = ref([]);
const details = ref({
  name: "",
  time: "",
  tiele: "",
  con: ""
});
//分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

//点击消息
const goToDetail = async e => {
  isStep1.value = 2;
  details.value = e;
  // console.log(e);
  // //已读
  await readMsg(e.id);
  // let data = {
  //   id: e.id
  // };
  // //详情
  // msgDetail(data).then(res => {
  //   // isStep1.value = 2;
  //   //获取details
  //   // details.value = res.data;
  //   // res.data.created_at = dateTimeZone(
  //   //   res.data.created_at,
  //   //   "{y}-{m}-{d} {h}:{i}:{s}",
  //   //   main.timeZone
  //   // );
  //   // console.log(res.data.created_at);
  // });
};

const backToStep1 = async () => {
  isStep1.value = 1;
  notifyList.value = [];
  await getMsgList();
};
const closeNotify = () => {
  console.log("closeNotifycloseNotifycloseNotify");
  emit("notifyClose");
};
const unread_num = ref(0);
//接口-------已读消息
const readMsg = async id => {
  let data = {
    id
  };
  let res = await msgRead(data);
  if (res.errno == 0) {
    // notifyList.value.forEach(item => {
    //   if ((item.id = id)) {
    //     item.status = 2;
    //   }
    // });
  }
  console.log(res);
};
//接口-------全部已读
const readAll = async () => {
  let res = await msgReadAll();
  console.log(res);
  if (res.errno == 0) {
    //清空
    notifyList.value = [];
    //请求
    await getMsgList();
  }
};

//接口-------获取消息列表
const getMsgList = async () => {
  let params = {
    page: currentPage.value,
    page_size: pageSize.value
  };
  let res = await msgList1(params);
  // console.log("接口列表", res);
  if (res?.errno == 0) {
    loading.value = false;
    res.data.list.forEach(item => {
      item.created_at = dateTimeZone(
        item.created_at,
        "{y}-{m}-{d} {h}:{i}:{s}",
        main.timeZone
      );
    });

    const messageTemplates = {
      active_bonus: t("layer.activity.getJb"),
      deposit_success: t("layer.activity.czJb"),
      deposit_bank_refused: t("layer.activity.banck"),
      withdrawal_success: t("layer.activity.withdrawal_success"),
      withdrawal_refused: t("layer.activity.withdrawal_refused"),
      vip_upgrade: t("layer.activity.vip_upgrade"),
      register: t("layer.activity.register")
    };

    function replaceMessageTemplate(data) {
      // 遍历数组中的每个对象
      return data.map((item, index) => {
        // 检查对象是否有tag属性，并且模板是否存在
        if (item.tag && messageTemplates[item.tag]) {
          // 获取对应语言的消息模板
          const template = messageTemplates[item.tag];
          if (template && item.msg && item.msg.length) {
            // 使用msg数组中的值替换模板中的占位符
            let content = template;
            item.msg.forEach((msgPart, index) => {
              content = content.replace(new RegExp(`%s`), t(msgPart));
            });
            item.content = content;
          }
        }
        return item;
      });
    }

    // 调用函数，传入数据和语言环境（默认为英文）
    const localizedMessages = replaceMessageTemplate(res.data.list);
    // i18n.global.locale.value

    notifyList.value.push(...localizedMessages);
    console.log("*/*/*////localizedMessages", localizedMessages);

    currentPage.value = res.data.page; //当前页
    pageSize.value = res.data.page_size; //总页数
    total.value = res.data.total; //总页数
    unread_num.value = res.data.unread_num; //未读数
  }
};

const bottom = ref(false);
const scrolling = async e => {
  const clientHeight = e.target.clientHeight;
  const scrollHeight = e.target.scrollHeight;
  const scrollTop = e.target.scrollTop;
  // console.log(clientHeight, scrollHeight, scrollTop);
  // console.log(scrollTop + clientHeight, scrollHeight, scrollTop);

  if (scrollTop + clientHeight >= scrollHeight) {
    console.log("到底了!");
    // console.log(notifyList.value.length);
    // console.log(total.value);.
    if (notifyList.value.length < total.value) {
      // loading.value = true;
      //数据未加载完，继续赋值
      currentPage.value++;
      getMsgList();
    }

    bottom.value = true;
  } else {
    bottom.value = false;
  }
};
onMounted(() => {
  // console.log("notify");
  if (main.isLogin) {
    getMsgList();
  }
});
watch(
  () => main.isLogin,
  () => {
    // console.log("消息监听登录状态", main.isLogin);
    if (main.isLogin) {
      getMsgList();
    }
  }
);

onBeforeUnmount(() => {});
</script>
<style scoped lang="less">
.van-overlay {
  top: 60px;
  background-color: #0f212e;
  z-index: 11 !important;
}
::v-deep(.van-dialog) {
  width: 99%;
  padding: 16px 10px;
  background-color: #0f212e !important;
}
@media (min-width: 600px) {
  .van-overlay {
    width: 375px;
    height: auto;
    max-height: 400px;
    overflow-y: auto;
    right: 45px;
    top: calc(60px + 0.5rem);
    left: unset;
    border-radius: 0.5rem;
    z-index: 11 !important;
  }

  .backIcon {
    display: none !important;
  }
  .backIcon2 {
    display: block !important;
  }
  .list-box {
    max-height: 300px !important;
    overflow-y: auto;
    padding-right: 10px;
  }
}
.notify {
  /*width: 100%;*/
  /* width: 375px;*/
  /*height: 100%;*/
  background-color: #0f212e;
  color: #b1bad3;
  position: relative;
}
.backIcon {
  display: block;
}
.list-box {
  max-height: calc(100vh - 320px);
  overflow-y: auto;
  padding-right: 10px;
}
.backIcon2 {
  display: none;
}
</style>
